package com.example.oms.controller;

import com.example.oms.dao.DiagRecordsDao;
import com.example.oms.dto.ReserveOfflineDto;
import com.example.oms.entity.Departments;
import com.example.oms.entity.Patients;
import com.example.oms.entity.Registrations;
import com.example.oms.entity.Schedule;
import com.example.oms.manager.DailyQueueManager;
import com.example.oms.service.PatientService;
import com.example.oms.service.UserService;
import com.example.oms.utils.DataResult;
import com.example.oms.vo.*;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("patient")
public class PatientController {

    @Resource
    PatientService patientService;
    @Resource
    private DailyQueueManager queueManager;
    @Resource
    UserService userService;

    //修改病人信息
    @PostMapping("editPatientInfo")
    public DataResult editPatientInfo(@RequestBody Patients patient){
        int i = patientService.editPatientInfo(patient);
        if(i==1)
            return new DataResult(200,patientService.getPatientById(patient.getId()),"修改成功");
        return new DataResult(201,null,"无改动");
    }

    //获取全部科室信息
    @GetMapping("/getAllDept")
    public DataResult getAllDept(){
        List<Departments> departmentsList = patientService.getAllDept();
        return new DataResult(200,departmentsList,"查询成功");
    }

    //获取某一天某一科室的所有医生
    @PostMapping("/getDoctorArrange")
    public DataResult getDoctorInOneDept(@RequestBody Map<String,String> map){
        int deptId = Integer.parseInt(map.get("deptid"));
        SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
        Date date;
        try {
            date = formatter.parse(map.get("date"));
        } catch (ParseException e) {
            return new DataResult(201,null,"日期格式错误");
        }
        List<DoctorArrangeInfoVo> doctorsList = patientService.getDoctorArrange(deptId,map.get("date"));
        return new DataResult(200,doctorsList,"查询成功");
    }

    //线上预约（未缴费）
    @PostMapping("/reserve")
    public DataResult reserve(@RequestBody Map<String, String> map){
        int patientId = Integer.parseInt(map.get("patientId"));
        int scheduleId = Integer.parseInt(map.get("scheduleId"));
        Schedule schedule = patientService.getReserveById(scheduleId);
        if(schedule.getNum()==0) {
            return new DataResult(201, null, "预约人数已满");
        }
        int reserveId = patientService.creatRegistration(schedule,patientId,1);
        if(reserveId == 0){
            return new DataResult(202,null,"请勿重复预约");
        }
        patientService.scheduleNumReduceOne(scheduleId);
        return new DataResult(200,reserveId,"预约成功");
    }
@Resource
    RedisTemplate redisTemplate;
    @PostMapping("/registerOffline")
    public DataResult registerOffline(@RequestBody Map<String,String>map)
    {
        String code=map.get("code");
        if(null!=code){
            if(!code.equals(redisTemplate.opsForValue().get(map.get("tel"))))
        return new DataResult(201,null,"验证码错误");
        }else return new DataResult(202,null,"验证码不能为空");
        int patientId;
        ReserveOfflineDto reserveOfflineDto=new ReserveOfflineDto();
        reserveOfflineDto.setIdNumber(map.get("IdNumber"));
        reserveOfflineDto.setTel(map.get("tel"));
        reserveOfflineDto.setName(map.get("name"));
        if(patientService.patientAccountNotExist(reserveOfflineDto.getIdNumber())){
            int userId = userService.creatAccount(reserveOfflineDto);
            patientService.creatPatient(reserveOfflineDto,userId);
            patientId = userId;
        }
        else {
            patientId = patientService.getPatientIdByIdNumber(reserveOfflineDto);
        }
    return new DataResult(200,patientId,"成功");
    }

    @PostMapping("/reserveOffline")
    public DataResult reserveOffline(@RequestBody Map<String,String>map){
        int patientId=Integer.valueOf(map.get("patientId"));

        int scheduleId = Integer.valueOf(map.get("scheduleId"));
        Schedule schedule = patientService.getReserveById(scheduleId);
        if(schedule.getNum()==0) {
            return new DataResult(201, null, "预约人数已满");
        }
        int reserveId = patientService.creatRegistration(schedule,patientId,0);

        if(reserveId == 0){
            return new DataResult(202,null,"请勿重复预约");
        }
        patientService.scheduleNumReduceOne(scheduleId);
        return new DataResult(200,reserveId,"预约成功");
    }
    //获取预约信息
    @GetMapping("/getRegistrationByPatientId")
    public DataResult getRegistrationByPatientId(@RequestParam int id){
        List<RegistrationInfoVo> registrationsList = patientService.getRegistrationInfoByPatientId(id);
        List<RegistrationInfoVo>list=new ArrayList<>();
        for (int i=0;i<registrationsList.size();i++){
            if(!"Canceled".equals(registrationsList.get(i).getStatus()))
                list.add(registrationsList.get(i));
        }
        return new DataResult(200,list,"预约信息查询成功");
    }
    @GetMapping("/getPaidRegistrationByPatientId")
    public DataResult getRegistrationByPatientId1(@RequestParam int id){
        List<RegistrationInfoVo> registrationsList = patientService.getRegistrationInfoByPatientId(id);
        List<RegistrationInfoVo>list=new ArrayList<>();
        for (int i=0;i<registrationsList.size();i++){
            if("Paid".equals(registrationsList.get(i).getStatus()))
                list.add(registrationsList.get(i));
        }
        return new DataResult(200,list,"预约信息查询成功");
    }

    @GetMapping("/getRegistrationByRegistrationId")
    public DataResult getRegistrationByRegistrationId(@RequestParam int id){
        Registrations registrationsList = patientService.getRegistrationByRegistrationId(id);

        return new DataResult(200,registrationsList,"预约信息查询成功");
    }

    //线上缴费完成（自动排队）
    @GetMapping("/addQueue")
    public DataResult addQueue(@RequestParam int id){

        Registrations registrations = patientService.getRegistrationById(id);
        int isReserved = registrations.getIsAppointmentRegistration();
        int patientId = registrations.getPatientId();
        int doctorId = registrations.getDoctorId();
        String period = registrations.getAppointmentPeriod();
        if(1==isReserved&&!userService.allowAddQueue(registrations.getAppointmentDate(),registrations.getAppointmentPeriod()))
        {
            return new DataResult(201,null,"时间未到不允许缴费");
        }
        patientService.editRegistrationsStatus(id,"Paid");
        Patients patient = patientService.getPatientById(patientId);
        int order = queueManager.addPatientToQueue(doctorId,patient,isReserved,period);
        return new DataResult(200,order,"入队成功");
    }

    //查看当前队列位置
    @PostMapping("/getOrder")
    public DataResult getOrder(@RequestBody Map<String,String> map){
        int patientId = Integer.parseInt(map.get("patientId"));
        List<RegistrationInfoVo> registrationInfoVos = patientService.getRegistrationInfoByPatientId(patientId);
        List<OrderInfoVo> res = new ArrayList<>();
        for (RegistrationInfoVo registrationInfoVo : registrationInfoVos) {
            if(registrationInfoVo.getStatus().equals("Paid")) {
                int doctorId = registrationInfoVo.getDoctorId();
                String period = registrationInfoVo.getAppointmentPeriod();
                OrderInfoVo orderInfoVo = new OrderInfoVo(
                        registrationInfoVo.getDoctorName(),
                        registrationInfoVo.getImage(),
                        registrationInfoVo.getDeptName(),
                        registrationInfoVo.getAppointmentDate(),
                        registrationInfoVo.getAppointmentPeriod(),
                        queueManager.getPatientPosition(doctorId, patientId, period)
                );
                res.add(orderInfoVo);
            }
        }
        return new DataResult(200,res,"所有预约的位次查询成功");
    }

    //所有待支付项目的信息
    @GetMapping("/getAllPay")
    public DataResult getAllPay(@RequestParam int id){
        List<RegistrationInfoVo> registrations = patientService.getNotPaidRegistrationByPatientId(id);
        List<PrescriptionsInfoVo> prescriptions = patientService.getNotPaidPrescriptionsByPatientId(id);
        List<DiagReportsInfoVo> diagReports = patientService.getNotPaidDiagReportsByByPatientId(id);
        NotPaidObjectVo res= new NotPaidObjectVo(registrations,prescriptions,diagReports);
        return new DataResult(200,res,"查询成功");
    }

    //查询患者所有的排队信息
    @GetMapping("/orders")
    public DataResult orders(@RequestParam int id){
        return null;
    }

    //取消预约
    @GetMapping("/cancelReserve")
    public DataResult cancelReserve(@RequestParam int reserveId){
        int cancelCount = patientService.cancelReserve(reserveId);
        if(cancelCount == 1)
            return new DataResult(200,null,"取消成功");
        return new DataResult(201,null,"取消异常");
    }
    @GetMapping("/addDetail")
    public DataResult addDetail(@RequestParam String idNumber, @RequestParam String name, HttpServletRequest request){
   return  userService.addDetail(idNumber,name,request);

    }
    @Resource
    DiagRecordsDao diagRecordsDao;
    @PostMapping("/getDiagId")
    public DataResult getDiagId(@RequestBody Map<String,String>map){
       List<Integer> list=diagRecordsDao.findIdbydoctorandpatient(map.get("doctorId"),map.get("patientId"));
        return new DataResult(200,list,"查询成功");

    }

}
